import IComponentServer from "../IComponentServer";
import { useStore } from "vuex";
import store from "../../store";
import userStore from '@/store/index.js';
import httpInterceptor from '@/utils/http.interceptor.js';

const conversationKey = "tim-conversation_uid:" + userStore.state.vuex_user.uid;

/**
 * class TUIConversationServer
 *
 * TUIConversation 逻辑主体
 */
export default class TUIConversationServer extends IComponentServer {
	public TUICore: any;
	public store = store.state.timStore;
	constructor(TUICore: any) {
		super();
		this.TUICore = uni.$TUIKit;
		uni.setStorageSync(`TIM_${uni.$chat_SDKAppID}_isTUIKit`, true);
		// #ifdef  APP-PLUS
		if (uni.$aegis) {
			uni.$aegis.reportEvent({
				name: 'platform',
				ext1: 'platform-APP-npm',
				ext2: 'uniTuikitExternalVue3',
				ext3: `${uni.$chat_SDKAppID}`,
			})
		}
		// #endif

		// #ifdef MP-WEIXIN  
		if (uni.$aegis) {
			uni.$aegis.reportEvent({
				name: 'platform',
				ext1: 'platform-MP-WEIXIN',
				ext2: 'uniTuikitExternalVue3',
				ext3: `${uni.$chat_SDKAppID}`,
			})
		}
		// #endif

		// #ifdef H5
		if (uni.$aegis) {
			uni.$aegis.reportEvent({
				name: 'platform',
				ext1: 'platform-H5-npm',
				ext2: 'uniTuikitExternalVue3',
				ext3: `${uni.$chat_SDKAppID}`,
			})
		}
		// #endif
		uni.showLoading({ title: 'Loading' });
		this.bindTIMEvent();
		// console.log("来加载拉")
		// console.log("来加载拉", uni.$chat_isSDKReady)
		this.getLocalCacheConversation();
		if (uni.$chat_isSDKReady) {
			this.getConversationList();
		}
	}

	/**
	 * /////////////////////////////////////////////////////////////////////////////////
	 * //
	 * //                                    TIM 事件监听注册接口
	 * //
	 * /////////////////////////////////////////////////////////////////////////////////
	 */

	private bindTIMEvent() {
		this.TUICore.on(
			uni.$TIM.EVENT.CONVERSATION_LIST_UPDATED,
			this.handleConversationListUpdate,
			this
		);
	}

	private unbindTIMEvent() {
		this.TUICore.off(
			uni.$TIM.EVENT.CONVERSATION_LIST_UPDATED,
			this.handleConversationListUpdate
		);
	}

	public handleConversationListUpdate(res: any) {
		uni.hideLoading();
		if (res.data.length === 0) {

		}
		// console.log("用户 ID", userStore.state.vuex_user.uid)
		// console.log("更新的会话列表哦。。。。", res)
		this.saveLocalCacheConversation(res.data);
		// store.commit("timStore/setConversationList", res.data);
	}

	/**
	 * 组件销毁
	 *
	 */
	public destroyed() {
		this.unbindTIMEvent();
	}

	/*
	 * 获取 conversationList
	 *
	 * @returns {Promise}
	 */
	private async getConversationList() {
		return new Promise<void>(async (resolve, reject) => {
			try {
				const imResponse = await uni.$TUIKit.getConversationList();
				this.saveLocalCacheConversation(imResponse.data.conversationList);
				if (this.store.conversationList.length == 0) {
					store.commit("timStore/setConversationList", imResponse.data.conversationList);
				}
				resolve(imResponse);
			} catch (error) {
				reject(error);
			}
		})
	}

	/**
	 * 获取 conversationList
	 *
	 * @param {string} conversationID 会话ID
	 * @returns {Promise}
	 */
	public async getConversationProfile(conversationID: string) {
		return new Promise<void>(async (resolve, reject) => {
			try {
				const imResponse = await this.TUICore.getConversationProfile(
					conversationID
				);
				resolve(imResponse);
			} catch (error) {
				reject(error);
			}
		});
	}

	/**
	 * 删除会话
	 *
	 * @param {string} conversationID 会话ID
	 * @returns {Promise}
	 */

	public async deleteConversation(conversationID: string) {
		return new Promise<void>(async (resolve, reject) => {
			try {
				const imResponse: any = await this.TUICore.deleteConversation(
					conversationID
				);
				resolve(imResponse);
			} catch (error) {
				reject(error);
			}
		});
	}

	/**
	 * 置顶会话
	 *
	 * @param {Object} options 置顶参数
	 * @returns {Promise}
	 */
	public async pinConversation(options: any) {
		return new Promise<void>(async (resolve, reject) => {
			try {
				const imResponse: any = await this.TUICore.pinConversation(options);
				resolve(imResponse);
			} catch (error) {
				reject(error);
			}
		});
	}

	/**
	 * C2C消息免打扰
	 *
	 * @param {Object} options 消息免打扰参数
	 * @returns {Promise}
	 */
	public async muteConversation(options: any) {
		return new Promise<void>(async (resolve, reject) => {
			try {
				const imResponse: any = await this.TUICore.setMessageRemindType(
					options
				);
				resolve(imResponse);
			} catch (error) {
				reject(error);
			}
		});
	}

	/**
	 * 设置已读
	 *
	 * @param {string} conversationID 会话ID
	 * @returns {Promise}
	 */
	public async setMessageRead(conversationID: string) {
		return new Promise<void>(async (resolve, reject) => {
			try {
				const imResponse: any = await this.TUICore.setMessageRead({
					conversationID,
				});
				resolve(imResponse);
			} catch (error) {
				reject(error);
			}
		});
	}

	/**
	 * 保存 IM会话数据到本地
	 */
	public async saveLocalCacheConversation(conversationList: any) {
		
		if (conversationList.length == 0) {
			return
		}
		//获取当前时间
		var nowDate = new Date(new Date().toLocaleDateString());
		var timestamp = new Date(nowDate.getTime()-7*24*60*60*1000).getTime()
		timestamp=timestamp/1000
		
		let data = []
		data = uni.getStorageSync(conversationKey) || [];
		if (data.length == 0) {
			uni.setStorageSync(conversationKey, conversationList);
			return;
		}
		//检查会话ID是否相同
		conversationList.forEach((item) => {
			let index = data.findIndex(e => {
				e.conversationID == item.conversationID
			})
			//判断如果是7天前的信息则将缓存中的数据赋值给conversationlist
			if(item.lastMessage.lastTime<timestamp){
				for(var i in data){
					if(data[i].conversationID==item.conversationID){
						item.isPinned=data[i].isPinned
					}
				}
			}else if(item.lastMessage.lastTime>timestamp){
				if (index > -1) {
					 data[index] = item;
				} else {
					data.push(item);
				}
			}
			//有则更新本地数据，无则追加最后
			// if (index > -1) {
			// 	data[index] = item;
			// } else {
			// 	data.push(item);
			// }
		})
		//按最后消息时间排序
		conversationList.sort((a,b) => b.lastMessage.lastTime - a.lastMessage.lastTime)
		//获取腾讯云会话ID
		let datalist = []
		for(var i in conversationList){
			 datalist[i]=conversationList[i].conversationID
		}
		//获取除腾讯云存储会话之外的全部会话
		httpInterceptor.get('/mgr/tim/chat/conversation/data',{conversation_ids: datalist}).then(res => {
			var conversationList2 =[]
			var sortconversationList =[]
			var unsortconversationList =[]
			var j=0
			for(var i in res){
				//判断该群是否已经解散
				if(res[i].type=="GROUP"&&res[i].groupProfile.name&&!res[i].isDelet){
					conversationList2[j]=res[i]
					j++
				}else if(res[i].type=="C2C"){
					conversationList2[j]=res[i]
					j++
				}
			}
			//对腾讯云会话和本地数据库会话进行拼接
			const conversationList1 = [
				...conversationList2,
				... conversationList,
			]
			//对列表数据进行排序
			var x=0
			var a=0
			for(var i in conversationList1){
				if(conversationList1[i].isPinned){
					sortconversationList[x]=conversationList1[i]
					x++
				}else{
					unsortconversationList[a]=conversationList1[i]
					a++
				}
			}
			//排序
			sortconversationList.sort((a,b) => b.lastMessage.lastTime - a.lastMessage.lastTime)
			unsortconversationList.sort((a,b) => b.lastMessage.lastTime - a.lastMessage.lastTime)
			const sortsconversationList = [
				...sortconversationList,
				... unsortconversationList,
				
			]
			// console.log("新的哦", sortsconversationList)
			uni.setStorageSync(conversationKey, sortsconversationList);
			store.commit("timStore/setConversationList", sortsconversationList);
		});
		//保存到本地
		// store.commit("timStore/setConversationList", conversationList);
		// uni.setStorageSync(conversationKey, conversationList);
	}
	
	/**
	 *  获取 本地IM会话数据
	 */
	public async getLocalCacheConversation() {
		let conversationList = []
		conversationList = uni.getStorageSync(conversationKey) || [];
		// console.log("本地的会话列表哦", conversationList)
		uni.hideLoading();
		store.commit("timStore/setConversationList", conversationList);
	}
}
